package com.tczs.web.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.tczs.dispatch.CustomerException;
import io.netty.util.internal.StringUtil;
import org.apache.log4j.Logger;

import java.text.ParseException;
import java.util.Date;

public class JWTUtil {
    private static Logger logger = Logger.getLogger(JWTUtil.class);

    //创建秘钥
    private static final byte[] SECRET = "d324gsgf32rfkdms32rfcfla3fkdsalpof".getBytes();

    //过期时间5秒
    private static final long EXPIRE_TIME = 1000 * 60 * 30;

    /**
     * 生成Token
     * @param account
     * @return
     */
    public static String buildJWT(String account) {
        try {
            //创建一个32-byte的密匙
            MACSigner macSigner = new MACSigner(SECRET);
            //建立payload 载体
            JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                    .subject(account) //主体
                    .issuer("http://www.tczs93.com")
                    .expirationTime(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                    .build();
            //3. 建立签名
            SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
            signedJWT.sign(macSigner);
            //4. 生成token
            String token = signedJWT.serialize();
            return token;
        } catch (KeyLengthException e) {
            e.printStackTrace();
        } catch (JOSEException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static String vaildToken(String token ) {
        if(StringUtil.isNullOrEmpty(token))
            throw new CustomerException("请先登录");
        try {
            SignedJWT jwt = SignedJWT.parse(token);
            JWSVerifier verifier = new MACVerifier(SECRET);
            //校验是否有效
            if (!jwt.verify(verifier)) {
                throw new CustomerException("非法登录");
            }
            //校验超时
            Date expirationTime = jwt.getJWTClaimsSet().getExpirationTime();
            if (new Date().after(expirationTime)) {
                throw new CustomerException("登录信息已过期");
            }
            //获取载体中的数据
            String subject = jwt.getJWTClaimsSet().getSubject();
            if (StringUtil.isNullOrEmpty(subject)){
                logger.error("非法登录,subject中无数据");
                throw new CustomerException("非法登录");
            }
            return subject;
        } catch (ParseException | JOSEException e) {
            logger.error("验收JWT代码发生错误",e);
            throw new CustomerException("无法解析token,非法登录");
        }
    }

    public static void main(String[] args){
        String root = buildJWT("root");
        System.out.println(root);
        String s = vaildToken(root);
     //   String s = vaildToken("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyb290IiwiaXNzIjoiaHR0cDpcL1wvd3d3LnRjenM5My5jb20iLCJleHAiOjE2MTcyNzI2MDR9.FkUM7FMEm9v4RZDh7PxiWvDwZfGHRX9Rg3NewWvbYdk");
        System.out.println(s);
    }
}
